package com.nannybear.View;

import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;

import com.jjoe64.graphview.DefaultLabelFormatter;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;

import java.util.ArrayList;

/**
 * \brief The drawing and graphics customization
 * \author Benjamin LANCINOT
 * \date 27-04-2015
 */

/********************************* COPYRIGHT *********************************
 * Copyright (c) 2015, Audrey LOISEAU and Benjamin LANCINOT.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *************************************************************************************/

public class GraphViewClass{
    /********** DECLARATIONS **********/
    // Variables
    private long timeToSee;
    private GraphView graphView;
    private LineGraphSeries<DataPoint> exampleSeries;
    private String colorGraph;
    private boolean isScrollable,isTemp;

    // Handler
    private final Handler myHandler = new Handler();

    /************ METHODS ************/
    /**
     * \brief Constructor
     */
    public GraphViewClass(boolean isTemperature){
        init();
        this.isTemp = isTemperature;
    }

    /**
     * \brief Initialization of the graphic
     */
    private void init(){
        colorGraph = "#8E3557";
        isScrollable = false;
        this.exampleSeries = new LineGraphSeries<>();
    }

    /**
     * \brief Find the min value of the array list
     * \param arrayListData The list with all the value
     * \return the smallest value
     */
    public double findMinValue(ArrayList<DataPoint> arrayListData){
        double minValue = arrayListData.get(0).getY();
        for(int i = 1 ; i<arrayListData.size() ; i++){
            if(arrayListData.get(i).getY() < minValue && arrayListData.get(i).getY() > -50){
                minValue = arrayListData.get(i).getY();
            }
        }
        return minValue;
    }

    /**
     * \brief Find the max value of the array list
     * \param arrayListData The list with all the value
     * \return the bigger value
     */
    public double findMaxValue(ArrayList<DataPoint> arrayListData){
        double maxValue = arrayListData.get(0).getY();
        for (int i = 1; i < arrayListData.size(); i++) {
            if (arrayListData.get(i).getY() > maxValue) {
                maxValue = arrayListData.get(i).getY();
            }
        }
        return maxValue;
    }

    /**
     * \brief Reception of a new arrayList
     * \param tempList  The new array list
     */
    public void update(ArrayList<DataPoint> tempList) {
            refreshWithNewData(tempList, findMinValue(tempList), findMaxValue(tempList));
    }

    /**
     * \brief Customize the graphView
     */
    public void customizeGraphView() {
        graphView.addSeries(exampleSeries);

        // Customize the grid of the graphic
        graphView.getGridLabelRenderer().setGridColor(Color.WHITE);
        graphView.getGridLabelRenderer().setHorizontalLabelsColor(Color.WHITE);
        graphView.getGridLabelRenderer().setVerticalLabelsColor(Color.WHITE);

        graphView.getGridLabelRenderer().setVerticalLabelsAlign(Paint.Align.RIGHT);
        graphView.getGridLabelRenderer().setNumHorizontalLabels(7);
        graphView.getGridLabelRenderer().setNumVerticalLabels(6);

        // Customize the line
        exampleSeries.setColor(Color.parseColor(colorGraph));
        exampleSeries.setDrawDataPoints(true);
        exampleSeries.setDataPointsRadius(2);
        exampleSeries.setThickness(4);


        graphView.getGridLabelRenderer().setLabelFormatter(new DefaultLabelFormatter() {
            @Override
            public String formatLabel(double value, boolean isValueX) {
                //generate X-axis label
                if (isValueX) {
                    int sec = Double.valueOf(value%60).intValue();
                    value = value / 60;
                    int min = Double.valueOf(value % 60).intValue();
                    value = value / 60;
                    int hour = Double.valueOf(value).intValue();
                    if (hour == 0) {
                        if (min == 0) {
                            if (sec != 0) {
                                return super.formatLabel(-sec, true) + "sec " ;
                            } else {
                                return super.formatLabel(sec, true);
                            }

                        } else {
                            return super.formatLabel(-min, true) + "min" + super.formatLabel(-sec, true) + "sec ";
                        }
                    } else {
                        return super.formatLabel(-hour, true) + "h" + super.formatLabel(-min, true) + "min ";
                    }
                }
                //generate Y-axis label
                else {
                    int tmp = (int)(value *10);
                    value = tmp/10.0;
                    if (isTemp) {
                        return "    " + super.formatLabel(value, false) + "°C   ";
                    }else{
                        if(value>=0) {
                            return "    " + super.formatLabel(value, false) + " %   ";
                        }else{
                            return "    " + super.formatLabel(0, false) + " %   ";
                        }
                    }
                }
            }
        });
    }

    /**
     * \brief Redraw the graph
     * \param arrayListData The array list
     * \param minData   The smallest data
     * \param maxData   The biggest data
     */
    public void redrawGraphwithNewData(ArrayList<DataPoint> arrayListData, double minData, double maxData){
        //Recover the array list for display it
        DataPoint[] listOfPoint = arrayListData.toArray(new DataPoint[arrayListData.size()]);
        // set manual X bounds
        if (arrayListData.size() > 0) {
            graphView.getViewport().setYAxisBoundsManual(true);
            graphView.getViewport().setMinY(minData - 1.5);
            graphView.getViewport().setMaxY(maxData + 1.5);

            // Draw in the view until the time to see
            if (arrayListData.get(0).getX() > -timeToSee) {
                graphView.getViewport().setXAxisBoundsManual(true);
                graphView.getViewport().setMinX(arrayListData.get(0).getX());
                isScrollable = false;
            }
            // The view is set scrollable just one time
            else if (!isScrollable) {
                graphView.getViewport().setXAxisBoundsManual(true);
                graphView.getViewport().setMinX(-timeToSee);
                graphView.getViewport().setScrollable(true);
                isScrollable=true;
            }
            getExampleSeries().resetData(listOfPoint);
        }
    }

    /**
     * \brief Handler to add data to the view
     */
    private void refreshWithNewData(final ArrayList<DataPoint> arrayListData, final double minData, final double maxData){
        myHandler.post(new Runnable() {
            @Override
            public void run() {
                redrawGraphwithNewData(arrayListData,minData, maxData);
            }
        });
    }

    /*********** ACCESSORS ***********/
    /**
     * \brief Get method for the graphView class
     */
    public GraphView getGraphView() {
        return graphView;
    }

    /**
     * \brief Get method for all the data
     */
    public LineGraphSeries<DataPoint> getExampleSeries() {
        return exampleSeries;
    }

    /**
     * \brief Set method for the time to see
     */
    public void setTimeToSee(long timeToSee) {
        this.timeToSee = timeToSee;
        isScrollable =false;
    }

    /**
     * \brief Set method for the graph color
     */
    public void setColorGraph(String colorGraph) {
        this.colorGraph = colorGraph;
    }

    /**
     * \brief Set method for the graphView class
     */
    public void setGraphView(GraphView graphView) {
        this.graphView = graphView;
    }
}
